package com.alibobo.bigsixnineapp.services.imp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import android.os.Environment;

import com.alibobo.utils.file.PathUtils;

public class SDFileIO {
	protected String SDlocalPath = "BigsixNine";

	protected String _rootPath;

	protected String rootPath() {

		return _rootPath;
	}

	public SDFileIO(String rootName) {
		if (rootName != null)
			SDlocalPath = rootName;
		_rootPath = initPath(SDlocalPath);
	}

	protected String initPath(String p) {

		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_REMOVED)) {
			File SDCardpath = Environment.getExternalStorageDirectory();
			String r = PathUtils.join(SDCardpath.getAbsolutePath(), p, "/");
			File myDataPath = new File(r);
			if (!myDataPath.exists())
				myDataPath.mkdirs();

			return r;
		}
		return "";

	}

	public InputStream readFile(String fileName) throws Exception {

		String fn = PathUtils.join(rootPath(), fileName);
		return new FileInputStream(fn);
	}

	public Object readObject(String fileName) {
		try {
			InputStream in = readFile(fileName);
			ObjectInputStream oin = new ObjectInputStream(in);
			Object result = oin.readObject();
			oin.close();
			in.close();
			return result;
		} catch (Exception e) {
			return null;
		}

	}

	public Boolean writeObject(String fileName, Object obj) {

		try {
			OutputStream os = openFileForWrite(fileName);
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(obj);
			oos.flush();
			oos.close();
			os.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public OutputStream openFileForWrite(String fileName) throws Exception {
		String fn = PathUtils.join(rootPath(), fileName);
		return new FileOutputStream(fn);
	}

	public String readText(String fileName) {

		try {
			InputStream in = readFile(fileName);
			byte[] buffer = new byte[4096];

			int bytesRead;
			StringBuffer sb = new StringBuffer();
			while ((bytesRead = in.read(buffer)) > 0) {
				String page = new String(buffer, 0, bytesRead, "UTF-8");
				sb.append(page);
			}
			in.close();
			return sb.toString();
		} catch (Exception e) {

		}
		return null;
	}

	public Boolean writeText(String fileName, String content) {
		try {

			OutputStream o = openFileForWrite(fileName);
			o.write(content.getBytes("UTF-8"));
			o.flush();
			o.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}
